
var jwt = require('jsonwebtoken'),
    LRU = require('lru-cache'),
    options = {
        max: 10000,
        length: function (n, key) { return n * 2 + key.length },
        dispose: function (key, n) { n.close() },
        maxAge: 1000 * 60 * 60 * 24 * 7
    },
    lruCache = LRU(options);

var tokenDao = {
    secret: 'zyc',
    isRevoked: function (req, payload, done) {
        console.log('---------isRevoked-----------');
        console.log(req.get('token'));
        console.log(payload);

        if (payload) {
            var iat = payload.iat;
            // 是否被注销
            if (lruCache.get(iat)) {

                return done(null, false);

            } else {
                // 过期
                return done({ success: false, msg: 'token 过期',name:"UnauthorizedError" }, true);
            }

        } else {
            // 过期
            return done({ success: false, msg: 'token 过期' ,name:"UnauthorizedError"}, true);
        }

    },
    sign: function (_user) {
        console.log('token sign');
        var token = jwt.sign({
            exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 7),
            data: _user
        }, this.secret);



        this.cachedSecret(token);

        return token;
    },
    verify: function (token) {

        var decoded, userId;

        try {
            decoded = jwt.verify(token, this.secret);
        } catch (err) {
            // err
            console.log(err);
            decoded = false;
        }


        if (decoded !== false) {

            console.log('=-----verifi');
            console.log(decoded);
            userId = decoded['data']['_id'];
        }

        return userId;

    },
    cachedSecret: function (token) {
        jwt.verify(token, this.secret, function (err, decoded) {

            if (err) {
                console.log(err);
                return;
            }


            console.log('------------cachedSecret------------');
            console.log(decoded); // bar

            var iat = decoded.iat;

            lruCache.set(iat, token);
        });
    },
    destroy: function (token) {
        jwt.verify(token, this.secret, function (err, decoded) {

            if (err) {
                console.log(err);
                return;
            }

            console.log(decoded); // bar

            var iat = decoded.iat;

            lruCache.del(iat);
        });
    }
};


module.exports = tokenDao;

/*
var userId = tokenVerify(req);

if(userId == false){
    response.error(res, 'error', '用户已过期，请重新登录');
}*/